import React, { useEffect, useState } from "react";
import {
  Button,
  Table,
  Tag,
  Upload,
  message,
  Modal,
  Form,
  Input,
  Radio,
  DatePicker,
} from "antd";
import {
  BookOutlined,
  DropboxOutlined,
  StepForwardOutlined,
  TwitterOutlined,
  UploadOutlined,
  YoutubeOutlined,
} from "@ant-design/icons";
import service from "@/http/request";
import { createStyles } from "antd-style";
import dayjs from "dayjs";
import axios from "axios";

import MyInput from "@/components/MyInput";
import { render } from "less";

import { useSelector } from "react-redux";
import { title } from "@uiw/react-md-editor";

const useStyle = createStyles(({ css, token }) => {
  const { antCls } = token;
  return {
    customTable: css`
      ${antCls}-table {
        ${antCls}-table-container {
          ${antCls}-table-body,
          ${antCls}-table-content {
            scrollbar-width: thin;
            scrollbar-color: #eaeaea transparent;
            scrollbar-gutter: stable;
          }
        }
      }
    `,
  };
});

const Seed = () => {
  const [remainingDownloadCount, setRemainingDownloadCount] = useState(0);
  const role = useSelector((state) => state.user.role);
  const { styles } = useStyle();
  const [torrents, setTorrents] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [loading, setLoading] = useState(false);

  const fetchTorrents = async (page = 1, pageSize = 10) => {
    setLoading(true);
    try {
      const res1 = await service.get("/torrents", {
        params: {
          pageNum: page,
          pageSize: pageSize,
        },
      });
      const res2 = await service.get("/torrents/active-status", {
        params: {
          pageNum: page,
          pageSize: pageSize,
        },
      });
      console.log(res1);
      console.log(res2);
      const data1 = res1.records;
      const data2 = res2.records;

      const n = data1.length;
      for (let i = 0; i < n; i++) {
        data1[i].connected = data2[i].connected;
      }
      console.log(data1);
      setTorrents(data1 || []);
      setPagination({
        current: page,
        pageSize: pageSize,
        total: res1.total || 0,
      });
    } catch (err) {
      console.error("获取种子数据失败：", err);
    } finally {
      setLoading(false);
    }
  };

  const fetchRemainingDownloadCount = async () => {
    try {
      const res = await service.get('/users/downloads/remaining');
      // 假设接口返回的剩余次数直接在 res.data 或 res 中，需要根据实际接口调整
      setRemainingDownloadCount(res || 0);
    } catch (error) {
      console.error('获取剩余下载次数失败', error);
    }
  };

  useEffect(() => {
    fetchTorrents();
    fetchRemainingDownloadCount();
  }, []);

  const handleTableChange = (pagination) => {
    fetchTorrents(pagination.current, pagination.pageSize);
  };

  const DownLoad = async (id) => {
    const token = localStorage.getItem("token");
    try {
      const res = await axios.get(
        `http://172.20.10.6:8080/torrents/download-with-passkey/${id}`,
        {
          headers: {
            Authorization: token,
          },
          responseType: "blob",
        }
      );
      const disposition = res.headers["content-disposition"];
      let filename = "download.torrent";
      if (disposition && disposition.includes("filename=")) {
        const match = disposition.match(
          /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
        );
        if (match != null && match[1]) {
          filename = decodeURIComponent(match[1].replace(/['"]/g, ""));
        }
      }

      const blob = new Blob([res.data], { type: "application/x-bittorrent" });
      const downloadUrl = URL.createObjectURL(blob);

      const link = document.createElement("a");
      link.href = downloadUrl;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(downloadUrl);
      fetchRemainingDownloadCount();
    } catch (e) {
      message.error("无下载资格，请联系管理员！");
      return;
    }
  };

  const handleUpload = async (values) => {
    if (!uploadFile) {
      message.error("请先选择一个种子文件！");
      return;
    }

    const token = localStorage.getItem("token");
    const formData = new FormData();
    formData.append("file", uploadFile);
    formData.append("name", values.Filename);
    formData.append("category", values.FileKind);

    try {
      setEditLoading(true);
      await axios.post("http://172.20.10.6:8080/torrents/upload", formData, {
        headers: {
          Authorization: token,
          "Content-Type": "multipart/form-data",
        },
      });

      setInfoModalVisible(false);
      fetchTorrents();
      form.resetFields();
      setUploadFile(null);
      message.success("上传成功！");
    } catch (error) {
      console.error("上传失败", error);
      message.error("上传失败！");
    } finally {
      setEditLoading(false);
    }
  };

  const columns = [
    { title: "ID", dataIndex: "id", key: "id", fixed: "left", width: 80 },
    { title: "名称", dataIndex: "name", key: "name" },
    {
      title: "类别",
      dataIndex: "category",
      key: "category",
      render: (category) => {
        if (category === "MUSIC") {
          return (
            <Tag icon={<StepForwardOutlined />} color="#87d068">
              音乐
            </Tag>
          );
        } else if (category === "MOVIE") {
          return (
            <Tag icon={<YoutubeOutlined />} color="#cd201f">
              电影
            </Tag>
          );
        } else if (category === "EBOOK") {
          return (
            <Tag icon={<BookOutlined />} color="#3b5999">
              图书
            </Tag>
          );
        } else {
          return (
            <Tag icon={<DropboxOutlined />} color="#55acee">
              软件
            </Tag>
          );
        }
      },
    },
    {
      title: "文件大小",
      dataIndex: "size",
      key: "size",
      render: (size) => `${(size / 1024 / 1024).toFixed(2)} MB`,
    },
    {
      title: "上传时间",
      dataIndex: "uploadedAt",
      key: "uploadedAt",
      render: (uploadedAt) => dayjs(uploadedAt).format("YYYY年MM月DD日 HH:mm"),
    },
    {
      title: "促销类型",
      dataIndex: "promotionType",
      key: "promotionType",
      render: (category) => {
        if (category === "NONE") {
          return <Tag color="blue">无促销</Tag>;
        } else if (category === "FREE") {
          return <Tag color="green">免费</Tag>;
        }
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status) =>
        status === "ACTIVE" ? (
          <Tag color="#87d068">正常</Tag>
        ) : (
          <Tag color="#f50">不可下载</Tag>
        ),
    },
    {
      title: "连接性",
      key: "connected",
      render: (item) => {
        console.log(item.connected);
        return item.connected ? (
          <Tag color="#87d068">已连接</Tag>
        ) : (
          <Tag color="#f50">未连接</Tag>
        );
      },
    },
    {
      title: "操作",
      key: "action",
      fixed: "right",
      render: (_, record) => {
        const isAdmin = role === "ADMIN";
        const isActive = record.status === "ACTIVE";

        const renderButton = (label, onClick, disabled = false) => (
          <Button
            style={{
              width: "50px",
              marginRight:
                label === "管理" ? "10px" : label === "删除" ? "10px" : 0,
            }}
            onClick={onClick}
            disabled={disabled}
          >
            {label}
          </Button>
        );

        const downloadBtn = renderButton(
          "下载",
          () => DownLoad(record.id),
          !isActive
        );

        if (isAdmin) {
          return (
            <div>
              {renderButton("删除", () => delSeed(record.id))}
              {renderButton("管理", () => adminSeed(record.id))}
              {downloadBtn}
            </div>
          );
        } else if (!isAdmin && !isActive) {
          return downloadBtn;
        } else {
          return downloadBtn;
        }
      },
    },
  ];

  const delSeed = (id) => {
    setDelVisible(true);
    setAdminID(id);
  };

  const adminSeed = (id) => {
    setAdminVisible(true);
    setAdminID(id);
  };

  const deleteSeed = async (id) => {
    Modal.confirm({
      title: "确认删除该种子？",
      content: `删除后无法恢复，是否继续？`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        try {
          const token = localStorage.getItem("token");
          await service.delete(`http://172.20.10.6:8080/admin/torrents/${id}`, {
            headers: {
              Authorization: token,
            },
          });
          message.success("删除成功！");
          setDelVisible(false); // 关闭弹窗
          fetchTorrents(); // 重新加载列表
        } catch (error) {
          console.error("删除失败：", error);
          message.error("删除失败！");
        }
      },
    });
  };

  const adminSeedContent = async (id) => {
    Modal.confirm({
      title: "设置促销？",
      content: `促销时间为${timeSelected}分钟 `,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        try {
          await service.post(`/admin/torrents/promotions2`, {
            torrentId: id,
            promotionType: "FREE",
            durationMinutes: timeSelected,
          });
          message.success("设置促销成功！");
          setAdminVisible(false); // 关闭弹窗
          fetchTorrents(); // 重新加载列表
        } catch (error) {
          console.error("设置促销失败：", error);
          message.error("设置促销失败！");
        }
      },
    });
  };

  const canclePromotion = (id) => {
    Modal.confirm({
      title: "是否要取消促销？",
      content: `是否继续？ `,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        try {
          await service.delete(`/admin/torrents/promotions2/${id}`);
          message.success("取消促销成功！");
          setAdminVisible(false); // 关闭弹窗
          fetchTorrents(); // 重新加载列表
        } catch (error) {
          console.error("取消促销失败：", error);
          message.error("取消促销失败！");
        }
      },
    });
  };

  const [adminID, setAdminID] = useState(0);
  const [delVisible, setDelVisible] = useState(false);
  const [adminVisible, setAdminVisible] = useState(false);
  const [infoModalVisible, setInfoModalVisible] = useState(false);
  const [editLoading, setEditLoading] = useState(false);
  const [form] = Form.useForm();
  const options = [
    { label: "电影", value: "MOVIE" },
    { label: "音乐", value: "MUSIC" },
    { label: "软件", value: "SOFTWARE" },
    { label: "图书", value: "EBOOK" },
  ];
  const [FilenameVal, setFilenameVal] = useState("");
  const [uploadFile, setUploadFile] = useState(null);

  const searchSeed = async (seed, page = 1, pageSize = 20) => {
    console.log(seed);
    const res = await service.get("/torrents/search", {
      params: {
        keyword: seed,
        pageNum: page,
        pageSize: pageSize,
      },
    });
    console.log(res);
    setTorrents(res.records || []);
  };

  const disabledDate = (current) => {
    // Can not select days before today and today
    return current && current < dayjs().endOf("day");
  };

  const disabledDateTime = () => ({
    disabledHours: () => range(0, 24).splice(4, 20),
    disabledMinutes: () => range(30, 60),
    disabledSeconds: () => [55, 56],
  });

  const range = (start, end) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  };

  const timeChange = (value, dateString) => {
    const start = dayjs();
    const end = value;

    const diffInMinutes = end.diff(start, "minute");

    // console.log( diffInMinutes); // 输出：150

    setTimeSelected(diffInMinutes);
  };

  const [timeSelected, setTimeSelected] = useState();
  return (
    <div
      style={{ display: "flex", flexDirection: "column", alignItems: "center" }}
    >
      <div
        style={{
          width: "70vw",
          display: "flex",
          justifyContent: "space-between",
          marginBottom: 16,
        }}
      >
        <Button
          icon={<UploadOutlined />}
          type="primary"
          onClick={() => setInfoModalVisible(true)}
        >
          上传文件
        </Button>
        <div style={{
          height:'32px',
          display:'flex',
          alignItems:'center'
        }}>
        <span >剩余下载次数：{remainingDownloadCount}</span>
        </div>
        <MyInput onClick={(value) => searchSeed(value)} />
      </div>
      <Table
        className={styles.customTable}
        columns={columns}
        dataSource={torrents}
        rowKey="id"
        loading={loading}
        pagination={pagination}
        onChange={handleTableChange}
        scroll={{ x: "max-content", y: "80vh" }}
        style={{ width: "90vw", height: "70vh" }}
      />

      <Modal
        title="上传文件"
        open={infoModalVisible}
        onCancel={() => setInfoModalVisible(false)}
        onOk={() => form.submit()}
        confirmLoading={editLoading}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleUpload} // 👈 直接传入 handleUpload
        >
          <Form.Item
            label="文件名称"
            name="Filename"
            rules={[{ required: true, message: "请输入文件名" }]}
          >
            <Input
              value={FilenameVal}
              onChange={(e) => setFilenameVal(e.target.value)}
            />
          </Form.Item>
          <Form.Item
            label="文件类型"
            name="FileKind"
            rules={[{ required: true, message: "文件类型" }]}
          >
            <Radio.Group block options={options}  />
          </Form.Item>
          <Form.Item>
            <Upload
              accept=".torrent"
              showUploadList={true}
              beforeUpload={(file) => {
                setUploadFile(file);
                return false; // 阻止自动上传
              }}
            >
              <Button icon={<UploadOutlined />} type="primary">
                选择文件
              </Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="删除种子"
        open={delVisible}
        onCancel={() => setDelVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setDelVisible(false)}>
            关闭
          </Button>,
          <Button key="delete" danger onClick={() => deleteSeed(adminID)}>
            删除种子
          </Button>,
        ]}
      >
        <div>种子编号：{adminID}</div>
      </Modal>

      <Modal
        title="设置促销"
        open={adminVisible}
        onCancel={() => setAdminVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => canclePromotion(adminID)}>
            取消促销
          </Button>,
          <Button key="delete" onClick={() => adminSeedContent(adminID)}>
            设置促销
          </Button>,
        ]}
      >
        <div>种子编号：{adminID}</div>
        <span>截止时间：</span>
        <DatePicker
          format="YYYY-MM-DD HH:mm:ss"
          title="截止时间"
          disabledDate={disabledDate}
          disabledTime={disabledDateTime}
          showTime={{ defaultValue: dayjs("00:00:00", "HH:mm:ss") }}
          onChange={timeChange}
        />
      </Modal>
    </div>
  );
};

export default Seed;
